package com.snowwolf.snowmail.core.datasource;


import com.snowwolf.snowmail.io.BodyStreamWrapper;

import javax.activation.DataSource;
import javax.activation.FileTypeMap;
import java.io.*;

/**
 * Created by snowwolf-louis on 17/11/23.
 */
public class InputStreamDataSource implements DataSource {
    private byte[] body;

    private String fileName;

    public InputStreamDataSource(InputStream is, String fileName) throws IOException {
        this.body = BodyStreamWrapper.inputStream2byte(is);
        this.fileName = fileName;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(body);
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        InputStream in = getInputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream;
    }

    @Override
    public String getContentType() {
        return FileTypeMap.getDefaultFileTypeMap().getContentType("");
    }

    @Override
    public String getName() {
        return fileName;
    }
}
